import React, { useState, useCallback, useRef, useEffect  } from 'react';
import { Table, Button, Tag, Row, Col } from 'antd';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import update from 'immutability-helper';
import { RightOutlined, LeftOutlined } from '@ant-design/icons';
import styles from './style.less';

const type = 'DragableBodyRow';

const LeftDragableBodyRow = ({ index, moveLeftRow, className, style, ...restProps }) => {
  const ref = useRef();
  const [{ isOver, dropClassName }, drop] = useDrop(
    () => ({
      accept: type,
      collect: monitor => {
        const { index: dragIndex } = monitor.getItem() || {};
        if (dragIndex === index) {
          return {};
        }
        return {
          isOver: monitor.isOver(),
          dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
        };
      },
      drop: item => {
        if (moveLeftRow) {
          moveLeftRow(item.index, index);
        }
      },
    }),
    [index],
  );
  const [, drag] = useDrag(
    () => ({
      type,
      item: { index },
      collect: monitor => ({
        isDragging: monitor.isDragging(),
      }),
    }),
    [index],
  );
  drop(drag(ref));

  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};

const RightDragableBodyRow = ({ index, moveRightRow, className, style, ...restProps }) => {
  const ref = useRef();
  const [{ isOver, dropClassName }, drop] = useDrop(
    () => ({
      accept: type,
      collect: monitor => {
        const { index: dragIndex } = monitor.getItem() || {};
        if (dragIndex === index) {
          return {};
        }
        return {
          isOver: monitor.isOver(),
          dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
        };
      },
      drop: item => {
        if (moveRightRow) {
          moveRightRow(item.index, index);
        }
      },
    }),
    [index],
  );
  const [, drag] = useDrag(
    () => ({
      type,
      item: { index },
      collect: monitor => ({
        isDragging: monitor.isDragging(),
      }),
    }),
    [index],
  );
  drop(drag(ref));

  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};

const PickList = (props) => {
  const { titles, dataSource, targetKeys, rowKey, leftColumns, rightColumns, disabled} = props;

  const [leftData, setLeftData] = useState(dataSource);
  const [rightData, setRightData] = useState([]);
  useEffect(() => {
    props.onChange(rightData.map(item=>{
      return item[rowKey]
    }))
  }, [rightData])
  useEffect(()=>{
    if (targetKeys.length> 0) {
      //console.log((targetKeys)
      setLeftData(dataSource.filter(item=>{
        return targetKeys.indexOf(item.processId)< 0
      }))
      setRightData(dataSource.filter(item=>{
        return targetKeys.indexOf(item.processId)>-1
      }))
    }
  }, [])
  const [selectedLeftKeys, setSelectedLeftKeys] = useState([]);
  const [selectedRightKeys, setSelectedRightKeys] = useState([]);

  const leftComponents = {
    body: {
      row: LeftDragableBodyRow,
    },
  };

  const rightComponents = {
    body: {
      row: RightDragableBodyRow,
    },
  };

  const moveLeftRow = useCallback(
    (dragIndex, hoverIndex) => {
      const dragRow = leftData[dragIndex];
      setLeftData(
        update(leftData, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragRow],
          ],
        }),
      );
    },
    [leftData],
  );
  const moveRightRow = useCallback(
    (dragIndex, hoverIndex) => {
      const dragRow = rightData[dragIndex];
      setRightData(
        update(rightData, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragRow],
          ],
        })
      );
      // //console.log((rightData)
      // props.onChange(rightData.map(item=>{
      //   return item[rowKey]
      // }))
    },
    [rightData],
  );


  const leftRowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedLeftKeys(selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: disabled,
    }),
  };

  const rightRowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRightKeys(selectedRowKeys)
    },
    getCheckboxProps: (record) => ({
      disabled: disabled,
    }),
  };

  const toRight = ()=>{
    if (selectedLeftKeys === []) return;
    const leftDataTemp = leftData.filter(item=>{
      return selectedLeftKeys.indexOf(item[rowKey]) < 0
    })
    const rightDataTemp = rightData.concat(leftData.filter(item=>{
      return selectedLeftKeys.indexOf(item[rowKey]) > -1
    }))
    setLeftData(leftDataTemp)
    setRightData(rightDataTemp)
    // props.onChange(rightDataTemp.map(item=>{
    //   return item[rowKey]
    // }))
  }

  const toLeft = ()=>{
    if (selectedRightKeys === []) return;
    const rightDataTemp = rightData.filter(item=>{
      return selectedRightKeys.indexOf(item[rowKey]) < 0
    })
    const leftDataTemp = leftData.concat(rightData.filter(item=>{
      return selectedRightKeys.indexOf(item[rowKey]) > -1
    }))
    setLeftData(leftDataTemp)
    setRightData(rightDataTemp)
    // props.onChange(rightDataTemp.map(item=>{
    //   return item[rowKey]
    // }))
  }

  return (
    <div className={'pickList'} style={{width: '100%'}}>
      <Row gutter={16}>
        <Col lg={10} md={12} sm={24}>
          <div style={{border: '1px solid #f0f0f0', height: '100%'}}>
            <div style={{padding: '16px', fontSize: '16px'}}>{titles[0]}</div>
            <DndProvider backend={HTML5Backend}>
              <Table
                rowKey={rowKey}
                columns={leftColumns}
                dataSource={leftData}
                size={'small'}
                rowSelection={{
                  ...leftRowSelection,
                }}
                scroll={{ y: 600 }}
                components={leftComponents}
                pagination={false}
                onRow={(record, index) => ({
                  index,
                  moveLeftRow,
                })}
              />
            </DndProvider>
          </div>


        </Col>
        <Col lg={4} md={12} sm={24} style={{display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
          <div className={'operation'} style={{width: '32px'}}>
            <Button type="primary" icon={<RightOutlined />} onClick={toRight} style={{marginBottom: '10px'}}/>
            <Button type="primary" icon={<LeftOutlined />} onClick={toLeft}/>
          </div>
        </Col>
        <Col lg={10} md={12} sm={24}>
          <div style={{border: '1px solid #f0f0f0', height: '100%'}}>
            <div style={{padding: '16px', fontSize: '16px'}}>{titles[1]}</div>
            <DndProvider backend={HTML5Backend}>
              <Table
                rowKey={rowKey}
                columns={rightColumns}
                dataSource={rightData}
                size={'small'}
                rowSelection={{
                  ...rightRowSelection,
                }}
                scroll={{ y: 600 }}
                pagination={false}
                components={rightComponents}
                onRow={(record, index) => ({
                  index,
                  moveRightRow,
                })}
              />
            </DndProvider>
          </div>
        </Col>
      </Row>
    </div>
  );
};
export default PickList;
